<template>
  <div class="settings-panel w-full">
    <n-tabs v-model:value="activeTab" type="line" animated>
      <!-- 基础设置 -->
      <n-tab-pane name="basic" tab="基础设置">
        <div class="space-y-4 p-4">
          <n-form-item label="主题模式" label-placement="left" label-width="100">
            <div class="flex items-center gap-2 w-full">
              <n-select
                v-model:value="settings.theme"
                :options="themeOptions"
                class="flex-1"
                @update:value="handleSettingChange"
              />
              <n-tag :type="themeStore.actualTheme === 'dark' ? 'warning' : 'success'" size="small">
                {{ themeStore.actualTheme === 'dark' ? '暗色' : '亮色' }}
              </n-tag>
            </div>
          </n-form-item>

          <n-form-item label="启用通知" label-placement="left" label-width="100">
            <n-switch
              v-model:value="settings.enableNotification"
              @update:value="handleSettingChange"
            />
          </n-form-item>

          <n-form-item label="自动保存" label-placement="left" label-width="100">
            <n-switch v-model:value="settings.autoSave" @update:value="handleSettingChange" />
          </n-form-item>
        </div>
      </n-tab-pane>

      <!-- 高级设置 -->
      <n-tab-pane name="advanced" tab="高级设置">
        <div class="space-y-4 p-4">
          <n-form-item label="开发者模式" label-placement="left" label-width="100">
            <n-switch v-model:value="settings.developerMode" @update:value="handleSettingChange" />
          </n-form-item>

          <n-divider />

          <div class="flex gap-4">
            <n-button type="error" @click="handleResetSettings">恢复默认</n-button>
            <n-button @click="handleOpenDevTools">开发者工具</n-button>
          </div>
        </div>
      </n-tab-pane>
    </n-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import {
  NTabs,
  NTabPane,
  NFormItem,
  NSelect,
  NSwitch,
  NButton,
  NDivider,
  NTag,
  useMessage,
  useDialog
} from 'naive-ui'
import logger from '../utils/logger'
import { useThemeStore } from '../stores/theme'

// 使用主题 store
const themeStore = useThemeStore()

// 设置接口 - 简化为扁平结构
interface Settings {
  theme: 'light' | 'dark' | 'auto'
  enableNotification: boolean
  autoSave: boolean
  developerMode: boolean
}

// 消息和对话框
const message = useMessage()
const dialog = useDialog()

// 当前激活的标签页
const activeTab = ref('basic')

// 默认设置
const defaultSettings: Settings = {
  theme: 'auto',
  enableNotification: true,
  autoSave: true,
  developerMode: false
}

// 设置数据 - 使用 ref 而不是 reactive
const settings = ref<Settings>({ ...defaultSettings })

// 主题选项
const themeOptions = [
  { label: '亮色', value: 'light' },
  { label: '暗色', value: 'dark' },
  { label: '跟随系统', value: 'auto' }
]

// 加载设置
const loadSettings = async (): Promise<void> => {
  try {
    const savedSettings = await window.api.getAppConfig('settings')
    if (savedSettings) {
      settings.value = { ...defaultSettings, ...savedSettings }
      // 同步主题到 store
      themeStore.setThemeMode(settings.value.theme)
      logger.debug('设置加载成功')
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    logger.error(`加载设置失败: ${errorMessage}`)
  }
}

// 保存设置 - 转换为普通对象
const saveSettings = async (): Promise<void> => {
  try {
    // 将 ref 转换为普通对象，确保可以通过 IPC 传递
    const settingsData = JSON.parse(JSON.stringify(settings.value))
    await window.api.saveAppConfig('settings', settingsData)
    logger.success('设置已保存')
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : '未知错误'
    logger.error(`保存设置失败: ${errorMessage}`)
    message.error('保存设置失败')
  }
}

// 设置变更处理
const handleSettingChange = (): void => {
  saveSettings()
}

// 监听主题变化，实时应用
watch(
  () => settings.value.theme,
  (newTheme) => {
    themeStore.setThemeMode(newTheme)
    logger.debug(`主题已切换为: ${newTheme}`)
  }
)

// 恢复默认设置
const handleResetSettings = (): void => {
  dialog.warning({
    title: '恢复默认设置',
    content: '确定要恢复所有设置到默认值吗？',
    positiveText: '确定',
    negativeText: '取消',
    onPositiveClick: () => {
      settings.value = { ...defaultSettings }
      saveSettings()
      message.success('已恢复默认设置')
      logger.debug('已恢复默认设置')
    }
  })
}

// 打开开发者工具
const handleOpenDevTools = (): void => {
  logger.debug('打开开发者工具')
  window.electron?.ipcRenderer.send('open-devtools')
}

// 组件挂载时加载设置
onMounted(async () => {
  await loadSettings()
})

// 暴露方法给父组件
defineExpose({
  loadSettings,
  saveSettings
})
</script>

<style scoped>
.settings-panel {
  max-width: 600px;
  margin: 0 auto;
}
</style>
